package com.bnz.servlet;

import com.bnz.pojo.Cart;
import com.bnz.pojo.Product;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 得到请求参数cmd的值
        String cmd = req.getParameter("cmd");
        // 2. 根据请求参数跳转到不同的方法
        if (StringUtils.isNotBlank(cmd)){
            // 1.2.1 添加到购物车
            if ("add".equals(cmd)){
                add(req,resp);
            }
        }
    }
    //1. 添加到购物车
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.1 得到参数pid的值
        String pid = req.getParameter("pid");
        // 1.2 得到servletContext对象
        ServletContext servletContext = req.getServletContext();
        // 1.3 得到servletContext对象里面的products属性值
        Map<String,Product> products = (Map<String,Product>)servletContext.getAttribute("products");
        // 1.4 根据pid(key)得到值
        Product product = products.get(pid);
        // 1.5 得到session对象
        HttpSession session = req.getSession();
        // 1.6 得到session对象里面的购物车对象
        Cart cart = (Cart) session.getAttribute("cart");
        // 1.6.1 如果没有购物车就重新创建一个
        if (cart == null){
            cart = new Cart();
        }
        // 1.6.2 将商品添加到购物车中
        cart.add(product);
        // 1.6.3 重新将购物车放回到session对象中
        session.setAttribute("cart",cart);
        // 1.6.4 跳转到购物车页面
        resp.sendRedirect("/cart_list.jsp");
    }
}

